//
//  WebPayViewController.m
//  RenRen
//
//  Created by mac on 2018/2/22.
//

#import "WebPayViewController.h"
#import <WebKit/WebKit.h>
#import <Masonry/Masonry.h>
#import "OrderDetail.h"
#import "MOrder.h"
#import "OrderInfo.h"

@interface WebPayViewController ()<WKUIDelegate,WKNavigationDelegate, WKScriptMessageHandler>

@property (nonatomic, strong)WKWebView *webView;

@end

@implementation WebPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"支付订单";
    // Do any additional setup after loading the view.
    //进行配置控制器
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    //实例化对象
    configuration.userContentController = [WKUserContentController new];
    
    //调用JS方法
    [configuration.userContentController addScriptMessageHandler:self name:@"SeeOrderInfo"];
    

    _webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:configuration];
    [self.view addSubview:_webView];
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 40.0;
    configuration.preferences = preferences;

    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    
    
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://adm.zadtek.com/dps/index.php?order=%@", _orderid]]]];
    
//    [_webView loadHTMLString:@"<html><header><meta http-equiv=\"ContentType\" content=\"text/html; charset=utf-8\" /><script type=\"text/javascript\">function secondClick() {window.webkit.messageHandlers.removeNavigationBar.postMessage('remove navigationBar');}function showAlert(message){alert(message);}function thirdClick(){window.webkit.messageHandlers.SeeOrderInfo.postMessage('add navigationBar');}</script></header><body bgcolor=\"green\"><h2> 这里是第二种方式 </h2><br/><br/><button type=\"button\" onclick=\"secondClick()\">Click</button><button type=\"button\" onclick=\"thirdClick()\">ThirdClick!</button></body></html>" baseURL:nil];
    
    
}

- (void)getData {
    NSDictionary* arg = @{@"ince":@"get_order_detail",@"order_id":self.orderid};
    
    NetRepositories* repositories = [[NetRepositories alloc]init];
    [repositories netConfirm:arg complete:^(NSInteger react, NSDictionary *response, NSString *message) {
        if(react == 1){
            MOrder *entity = [[MOrder alloc] initWithItem:response[@"order"]];
            OrderInfo* controller = [[OrderInfo alloc]init];
            controller.hidesBottomBarWhenPushed = YES;
            controller.orderID = entity.rowID;
            controller.entity = entity;
            [self.navigationController pushViewController:controller animated:YES];
        }else if(react == 400){
            [self alertHUD:message];
        }else{
            [self alertHUD:message];
        }
    }];
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    //    message.body  --  Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
    NSLog(@"body:%@",message.body);
    if ([message.name isEqualToString:@"SeeOrderInfo"]) {
        NSLog(@"SeeOrderInfo");
        [self getData];
    }
}

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationActionPolicyCancel);
}
#pragma mark - WKUIDelegate
// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    return [[WKWebView alloc]init];
}
// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    completionHandler(@"http");
}
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    completionHandler(YES);
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSLog(@"%@",message);
    completionHandler();
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
